<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%String path = request.getContextPath();%>
<%@ taglib uri="/WEB-INF/tld/c.tld" prefix="c" %>
<%@ taglib uri="/WEB-INF/tld/ui.tld" prefix="ui" %>
<%@ taglib uri="/WEB-INF/tld/fmt.tld" prefix="fmt" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <c:set var="ctx" value="${pageContext.request.contextPath}" />
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>录入来款</title>
    <jsp:include page="../../import.jsp" flush="true"/>
</head>
<body class="iframeBody">
<form id="stl_form">
    <div class="fieldset1 tabel_col clearFix">
        <div class="fieldBox col_33">
            <div class="label">结清时间</div>
            <div class="field">
                <input ligerui="width:125" id="stlDt" type="text" value="${stlDt}" class="ui-datepicker" validate="{required:true}">
                <input id="prjPrdDtlId" name="prjPrdDtlId" value="${prjPrdDtlId}" type="text" style="display: none;">
                <span id="saveStlDtBtn" class="sq-button sq-button-round">保存</span>
            </div>
        </div>
        <div class="fieldBox col_66">
            <div class="label">应收结清款</div>
            <div class="field">
                <fmt:formatNumber value="${pay.stlAmt==null?null:pay.stlAmt/100}" pattern="0.##"/>
            </div>
        </div>
    </div>
</form>
<form id="capFund_form">
    <div class="fieldset1 tabel_col tabel_col_1 clearFix">
        <div class="caption">
            <span class="title">资金基本信息</span>
        </div>
        <div class="fieldBox col_33">
            <div class="label">资金编号</div>
            <div class="field">
                <a class="link" style="cursor: pointer;" onclick="qyDecompose();"><span id="fundCode">${capFundVO.code}</span></a>
            </div>
        </div>
        <div class="fieldBox col_33">
            <div class="label">来款户名</div>
            <div class="field">
                <div class="triggerPop1">
                    <input name="comeName" id="comeName" type="text" class="ui-textbox" value="${capFundVO.comeName}"
                           validate="{required:true,maxlength:64}">
                </div>
                <span class="requiredSymbol">*</span>
            </div>
        </div>
        <div class="fieldBox col_33">
            <div class="label">来款账号</div>
            <div class="field">
                <input name="comeCode" id="comeCode" type="text" class="ui-textbox" value="${capFundVO.comeCode}"
                       validate="{required:false,maxlength:21}">
            </div>
        </div>
        <div class="fieldBox col_33">
            <div class="label">来款金额</div>
            <div class="field">
                <input name="amount" id="amount" type="text" class="ui-textbox" value="" validate="{required:true,number:true}">
                <span class="requiredSymbol">*</span>
            </div>
        </div>
        <div class="fieldBox col_33">
            <div class="label">收款账户</div>
            <div class="field">
                <input name="acceptName" id="acceptName" type="text" class="ui-textbox" value="${capFundVO.acceptName}"
                       validate="{required:true,maxlength:64}">
                <span class="requiredSymbol">*</span>
            </div>
        </div>
        <div class="fieldBox col_33">
            <div class="label">收款账号</div>
            <div class="field">
                <input name="acceptCode" id="acceptCode" type="text" class="ui-textbox" value="${capFundVO.acceptCode}"
                       validate="{required:false,maxlength:64}">
                <span class="requiredSymbol">*</span>
            </div>
        </div>
        <div class="fieldBox col_33">
            <div class="label">交易(到账)日期</div>
            <div class="field">
                <input name="acceptDate" id="acceptDate" type="text" class="ui-datepicker"
                       value="${capFundVO.acceptDates}"
                       validate="{required:true}">
                <span class="requiredSymbol">*</span>
            </div>
        </div>
        <div class="fieldBox col_33">
            <div class="label">实际到账日期</div>
            <div class="field">
                <input name="acceptActualDate" id="acceptActualDate" type="text" class="ui-datepicker" value="${capFundVO.acceptActualDates}" validate="{required:true}">
                <span class="requiredSymbol">*</span>
            </div>
        </div>

        <div class="fieldBox col_33">
            <div class="label">事业部</div>
            <div class="field">
                <input name="fundBelongOrgCd" id="fundBelongOrgCd" data-value="${capFundVO.fundBelongOrgCd}" validate="{required:true}" placeholder="请选择" ltype="combobox">
                <span class="requiredSymbol">*</span>
            </div>
        </div>
        <div class="fieldBox col_100">
            <div class="label">摘要</div>
            <div class="field">
                <textarea name="docketRem" id="docketRem" class="ui-textarea l-textarea" value="${capFundVO.docketRem}"
                    rows="4" cols="120" style="width: 99%;" validate="{required:false,maxlength:2000}">${capFundVO.docketRem}</textarea>
                <input type="text" id="fundInputCd" name="fundInputCd" value="1" style="display:none;">
                <input type="text" id="relationPayId" name="relationPayId" value="${capFundVO.relationPayId}" style="display:none;">
                <input type="text" id="cstId" name="cstId" value="${capFundVO.cstId}" style="display:none;">
                <input type="text" id="cstNm" name="cstNm" value="${capFundVO.cstNm}" style="display:none;">
                <input type="text" id="identifyOperator" name="identifyOperator" value="${capFundVO.identifyOperator}" style="display:none;">
                <input type="text" id="identifyOperatorNm" name="identifyOperatorNm" value="${capFundVO.identifyOperatorNm}" style="display:none;">
                <input type="text" id="identifyTime" name="identifyTime" value="${capFundVO.identifyTime}" style="display:none;">
                <input type="text" id="fundSourcesCd" name="fundSourcesCd" value="${capFundVO.fundSourcesCd}" style="display:none;">
            </div>
        </div>
    </div>
    <div id="btnDiv" class="btnsBox">
        <span id="saveCapFund_Btn" class="sq-button sq-button-round l-dialog-btn-ok">保存</span>
        <input type="reset" id="resetBtn" class="l-button l-button-reset Hide">
    </div>
</form>
<div class="fieldset1 tabel_col tabel_col_1 clearFix">
    <div class="caption">
        <span class="title">资金列表</span>
    </div>
    <div class="fieldBox col_100">
        <div id="ligergrid_fundlist" class="sq-grid"></div>
    </div>
</div>

<div class="fieldset1 tabel_col tabel_col_1 clearFix">
    <div class="caption">
        <span class="title">保证金列表</span>
    </div>
    <div class="fieldBox col_100">
        <div id="feeOutGrid" class="sq-grid"></div>
    </div>
    <span id="searchBtn" class="sq-button sq-button-round Hide"></span>
    <span id="clearBtn" class="sq-button sq-button-round Hide"></span>
</div>

<script>
    var capFundId=null,fundGrid=null,feeOutGrid=null;
    var stlDtDisableFlag = '${stlDtDisableFlag}';
    $(function () {
        // 结清时间是否显示，0-否，1-是
        console.log("结清时间是否显示："+stlDtDisableFlag);
        if (stlDtDisableFlag && stlDtDisableFlag == '0'){
            $("#stl_form").addClass('Hide');
        }

        //事业部
        $("#fundBelongOrgCd").ligerComboBox({
            valueField: 'key',
            textField: 'value'
        });
        $("#capFund_form").ligerForm({
            validate: true,
            onAfterSetFields: function () {
                set_triggerPop1().click(function (event) {
                    var cstId = $("#cstId").val();
                    var cstNm = $("#cstNm").val();
                    var relationPayId = $("#relationPayId").val();
                    $.ligerDialog.SQopen({
                        width: 950,
                        height: 490,
                        title: '选择资金列表',
                        url: '<%=path%>/capital/capFund/toChooseFund.do?type=1&bizTypCd=1&relationPayId=' + relationPayId + '&cstId=' + cstId + '&cstNm=' + cstNm,
                        fixButtons: true,
                        allowClose: false,
                    });
                });
            }
        });
        //给输入框添加三点...并返回此节点，可用于绑定事件
        function set_triggerPop1() {
            var $triggerBtn = $('<div class="l-text-popup"><div class="l-trigger"><div class="l-trigger-icon"></div></div></div>');
            $('.triggerPop1 .l-text').append($triggerBtn);
            return $triggerBtn;
        };

        $("#stl_form").ligerForm({
            validate: true
        });

        liger.get("fundBelongOrgCd").setData(${fundBelongOrgCdList});

        var amount='${amount}';
        if(amount){
            $("#amount").val(amount);
        }


        fundGrid = $("#ligergrid_fundlist").ligerGrid({
            url: '<%=path%>/capital/capFund/initFundList.do',
            parms:{'cstId':${cstId},'relationPayId':'${capFundVO.relationPayId}'},
            method: 'get',
            columns: [
                {display: '资金编号', name: 'code', width: 130, align: 'left', enabledSort: false,
                    render:function(rowdata,index,value){
                        return '<a href="javascript:;" style="cursor: pointer;" onclick="qyFund('+rowdata.id+')">'+rowdata.code+'</a>';
                    }
                },
                {display: '收款账户', name: 'acceptName', minWidth: 100, align: 'left', enabledSort: false},
                {display: '交易(到账)日期', name: 'acceptDate', width: 100, align: 'center', enabledSort: false,render:renderDate},
                {display: '来款账号', name: 'comeCode', width: 150, align: 'left', enabledSort: false},
                {display: '来款户名', name: 'comeName', minWidth: 100, align: 'left', enabledSort: false},
                {display: '来款金额', name: 'amount', width: 110, align: 'right', enabledSort: false,
                    render:function(rowdata,index,value){
                        return '&yen;'+FormatMoney(rowdata.amount/100);
                    }
                },
                {display: '可用金额', name: 'availableAmount', width: 110, align: 'right', enabledSort: false,
                    render:function(rowdata,index,value){
                        return '&yen;'+FormatMoney(rowdata.availableAmount/100);
                    },
                    totalSummary:{
                        render: function (rowdata, column, cell){
                            if(rowdata.sum) {
                                var flag = $("#flag").val();
                                if ("6" == flag && "" != '${redeemId}' && null != '${redeemId}') {
                                    calcCstStlIrrAndDiscountAmt(rowdata, column, cell);
                                }
                                return '<div style="color:red">合计:' + '&yen;'+FormatMoney(rowdata.sum/100) + '</div>';
                            }else{
                                return '<div style="color:red">合计:' + '&yen;0.00</div>';
                            }
                        },
                        align: 'left'
                    },
                },
                {display: '客户名称', name: 'cstNm', width: 90, align: 'left', enabledSort: false,},
                {display: '操作', width: 120, align: 'center', enabledSort: false,
                    render:function(rowdata,index,value){
                        return "<a class='sq-button-hasicon' href='javascript:;' onclick='delFund("+rowdata.id+")'><i class='sqBtnIco_7'></i>删除</a>";
                    }
                },
            ],
            onDblClickRow:function(rowdata, rowid, rowobj){
                capFundId=rowdata.id;
                $("#fundCode").text(rowdata.code);
                $("#comeName").val(rowdata.comeName);
                $("#comeCode").val(rowdata.comeCode);
                $("#acceptName").val(rowdata.acceptName);
                $("#acceptCode").val(rowdata.acceptCode);
                $("#amount").val(rowdata.amount/100);
                $("#acceptDate").val(DateUtils.formatDate(new Date(rowdata.acceptDate),DateUtils.YYYY_MM_DD));
                $("#acceptActualDate").val(DateUtils.formatDate(new Date(rowdata.acceptActualDate),DateUtils.YYYY_MM_DD));
                $("#docketRem").text(rowdata.docketRem);
                liger.get("fundBelongOrgCd").setValue(rowdata.fundBelongOrgCd);
            },
            usePager: false,
            root: 'rows',
            record: 'total',
            hideLoadButton: true,
            width: '100%',
            height: '240',
            heightDiff: -2,
            checkbox: false,
            rownumbers: true,
            allowUnSelectRow: true,
            alternatingRow: true
        });

        feeOutGrid = $("#feeOutGrid").ligerGrid({
            url: '<%=path%>/capital/capFeeOutLog/initList.do?qtype=0&paySchId=${wsPaySchId}',
            method: 'get',
            columns: [
                {display: '支付表号', name: 'paySchNo', minWidth: 100, align: 'left', enabledSort: false},
                {display: '费用类型', name: 'feeTypCdNm', minWidth: 100, align: 'center', enabledSort: false},
                {display: '费用金额', name: 'feeAmt', minWidth: 100, align: 'right', enabledSort: false,
                    render:function(rowdata,index,value){
                        return '&yen;'+FormatMoney(rowdata.feeAmt/100);
                    }
                },
                {display: '转出金额', name: 'outAmt', minWidth: 100, align: 'right', enabledSort: false,
                    render:function(rowdata,index,value){
                        return '&yen;'+FormatMoney(rowdata.outAmt/100);
                    }
                },
                {display: '操作', name: '', minWidth: 100, align: 'left', enabledSort: false,
                    render:function(rowdata,index,value) {
                        if(rowdata.feeAmt>rowdata.outAmt){
                            //var amt=rowdata.feeAmt-rowdata.outAmt;
                            return "<a class='sq-button-hasicon' href='javascript:;' onclick='feeOut("+index+")'><i class='sqBtnIco_17'></i>转出</a>";
                        }
                    }
                }
            ],
            pageSize: 10,
            root: 'rows',
            record: 'total',
            hideLoadButton: true,
            width: '100%',
            height: '240',
            heightDiff: -2,
            checkbox: true,
            rownumbers: true,
            allowUnSelectRow: true,
            alternatingRow: false
        });

        var accDialog=null;
        $("#acceptName").focus(function(event) {
            accDialog=$.ligerDialog.SQopen({
                url: "<%=path%>/system/sysBkAccInfo/toChooseListPage.do",
                width: 800,
                height: 400,
                title: "选择收款账户"
            });
        });

        /*保存*/
        $("#saveCapFund_Btn").click(function (event) {
            var form = liger.get("capFund_form");
            if (!form.valid()) {
                top.$.ligerDialog.SQalert({content: LogUtils.LOG_CMM_MUST_FIX_ITEM_INFO, SQ_type: "warning"});
                return false; //验证不通过，不执行以下代码
            }
            var data = form.getData();
            //data["amount"]=parseFloat($("#amount").val()*100);
            $.ligerDialog.hide();
            var _url;
            if (!capFundId) {//新增
                _url = '<%=path%>/capital/capFund/add.do';
            } else {//修改
                _url = '<%=path%>/capital/capFund/modify.do?id=' + capFundId;
            }
            var wait_dialog;
            $.ajax({
                type: 'post',
                dataType: 'json',
                data: data,
                url: _url,
                beforeSend: function () {
                    wait_dialog = $.ligerDialog.SQalert({content: LogUtils.LOG_CMM_DATA_LOADING, SQ_type: "waitting"});
                },
                success: function (msg) {
                    wait_dialog.close();
                    if (msg.success == 1) {
                        liger.get('amount').setValue('');
                        liger.get('comeCode').setValue('');
                        liger.get('acceptDate').setValue('');
                        liger.get('acceptActualDate').setValue('');
                        $('#docketRem').val('');
                        top.$.ligerDialog.SQalert({content: msg.info, SQ_type: "success"});
                        fundGrid.reload();
                    } else {
                        top.$.ligerDialog.SQalert({content: msg.info, SQ_type: "error"});
                    }
                }
            });
        });

        /*关闭*/
        $("#closeBtn").click(function (event) {
            //frameElement.dialog.close();
        });

        /* 查询 */
        $("#searchBtn").click(function (event) {
            fundGrid.reload();
        });

        /* 清空 */
        $("#clearBtn").click(function (event) {
            feeOutGrid.reload();
        });


        /*保存*/
        $("#saveStlDtBtn").click(function (event) {
            var form = liger.get("stl_form");
            if (!form.valid()) {
                $.ligerDialog.SQalert({content: LogUtils.LOG_CMM_MUST_FIX_ITEM_INFO, SQ_type: "warning"});
                return false; //验证不通过，不执行以下代码
            }
            var data = form.getData();
            data['stlDt']=$("#stlDt").val();
            $.ligerDialog.hide();

            var wait_dialog;
            $.ajax({
                type: 'post',
                dataType: 'json',
                data: data,
                url: '<%=path%>/capital/capFund/modifyStlDt.do',
                beforeSend: function () {
                    wait_dialog = $.ligerDialog.SQalert({content: LogUtils.LOG_CMM_DATA_LOADING, SQ_type: "waitting"});
                },
                success: function (msg) {
                    wait_dialog.close();
                    if (msg.success == 1) {
                        top.$.ligerDialog.SQalert({content: msg.info, SQ_type: "success"});
                    } else {
                        $.ligerDialog.SQalert({content: msg.info, SQ_type: "error"});
                    }
                }
            });
        });

    });

    //查询资金信息
    function qyFund(_id) {
        var onCancel = function (item, Dialog) {
            Dialog.hide();
        };
        $.ligerDialog.SQopen({
            width: 800,
            //height: 300,
            autoFixHeight: true,
            title : '资金信息',
            url: "<%=path%>/capital/capFund/toFundDtlPage.do?id="+_id,
            buttons: [
                {
                    text: "关闭", onclick: onCancel, type: 'cancel'
                }
            ]
        });
    }

    //废除
    function delFund(id){
        var _ids = [id];
        $.ligerDialog.confirm("是否确认删除该笔资金?", function (flag) {
            if (flag == false)return;
            var wait_dialog;
            $.ajax({
                type: 'post',
                dataType: 'json',
                data: {ids: JSON.stringify(_ids)},
                url: '<%=path%>/capital/capFund/removeOnlyRelationPayIdByIds.do',
                beforeSend: function () {
                    wait_dialog = $.ligerDialog.SQalert({
                        content: LogUtils.LOG_CMM_DATA_LOADING,
                        SQ_type: "waitting"
                    });
                },
                success: function (msg) {
                    wait_dialog.close();
                    if (msg.success == 1) {
                        $.ligerDialog.SQalert({content: msg.info, SQ_type: "success"});
                        fundGrid.reload();
                    } else {
                        $.ligerDialog.SQalert({content: msg.info, SQ_type: "error"});
                    }
                }
            });
        });
    }

    /**
     * 新增或删除资金项重新计算结清对客irr和结清优惠金额1
     * @param rowdata
     * @param column
     * @param cell
     */
    function calcCstStlIrrAndDiscountAmt(rowdata, column, cell) {
        var redeemTypeCd = $("#redeemTypeCd").val();//赎回方式
        // 只判断赎回结清时计算
        if ("1" == redeemTypeCd) {
            var totalAvailableAmt = rowdata.sum;
            for (var i = 0; i < cell.rows.length; i++) {
                if ("2" == cell.rows[i].handleWayCd || "4" == cell.rows[i].handleWayCd) {
                    totalAvailableAmt = totalAvailableAmt - cell.rows[i].availableAmount;
                }
            }
            var url = "<%=path%>/ass/assTrailCarD/calcCstStlIrrAndDiscountAmt.do";
            $.ajax({
                type: 'get',
                dataType: 'json',
                data: {paySchId:'${wsPaySchId}', totalAvailableAmt:totalAvailableAmt, redeemId:'${redeem_Id}'},
                url: url,
                success: function (msg) {
                    if (msg.success == 1) {
                        $("#cstStlIrr").html(msg.data.cstStlIrr);
                        $("#redeemStlDiscountAmt1").html(msg.data.discountAmt);
                        var receivableAmt = $("#redeemAmt").val() - msg.data.discountAmt;
                        $("#receivableAmt").val(receivableAmt);
                    } else {
                        $.ligerDialog.SQalert({content: msg.info, SQ_type: "error"});
                    }
                }
            });
        }
    }

    //查看分解单
    function qyDecompose(){
        if(!capFundId){
            return;
        }
        Add_navTab('toDecomDtlPage_'+capFundId, "分解单查看", '<%=path%>/capital/capFund/toDecomDtlPage.do?fundId='+capFundId, null);
    }

    //格式化时间
    function renderDate(rowdata, index, value) {
        var dateStr = "";
        if (null != value) {
            var date = new Date(value);
            dateStr = DateUtils.formatDate(date, DateUtils.YYYY_MM_DD);
        }
        return dateStr;
    }

    function feeOut(index){
        var data=feeOutGrid.getRow(index);
        var amt=data.feeAmt-data.outAmt;
        var req="?paySchId="+data.paySchId+"&paySchNo="+data.paySchNo+"&paySchDId="+data.paySchDId+"&feeTypCd="+data.feeTypCd+ "&feeAmt=" + data.feeAmt +"&outAmt="+amt+"&relationId=${capFundVO.relationPayId}";
        $.ligerDialog.open({
            width: 550,
            height: 400,
            title: '保证金转出',
            url:'<%=path%>/capital/capFeeOutLog/toAddPage.do'+req,
            onClose: function () {
                top.$.ligerDialog.SQalert({content: "保证金转出成功！",SQ_type: "success"});
                feeOutGrid.reload();
            }
        });
    }
</script>
</body>
</html>
